# encoding=utf-8
import tkinter
import time
from tkinter import messagebox
import hashlib
from chat.client.utils.sender import socket_send_msg
from client.auth.auth import *
from chat.client.rooms.rooms import socket_send_userid, socket_get_room_history
import chat.client.gol
from chat.client.utils.recver import recver_thread


def start_thread():
    thread = chat.client.utils.recver.recver_thread()
    thread.start()


def pwd_cls_btn():
    '''
    这是主界面，账户密码登录界面的关闭按钮
    '''
    print("这是主界面，账户密码登录界面的关闭按钮")
    login.destroy()
    exit(0)

chat.client.gol._init()
login = tkinter.Tk()
login.title("登录")
login.geometry('250x200')
tkinter.Label(login, text='登录').grid(row=0, column=0, columnspan=2)
tkinter.Label(login, text='用户名：').grid(row=1, column=0)
name = tkinter.Entry(login)
name.grid(row=1, column=1)
tkinter.Label(login, text='密  码：').grid(row=2, column=0, sticky=tkinter.E)
passwd = tkinter.Entry(login, show='*')
passwd.grid(row=2, column=1)
login.protocol('WM_DELETE_WINDOW', pwd_cls_btn)
login.resizable(0, 0)


def register_cls_btn():
    """
    打开新窗口时需要隐藏主窗口
    但这时关闭新窗口会导致主窗口一直隐藏
    故DISABLE掉新窗口的关闭按钮
    :return:
    """
    print("这是注册界面的关闭按钮，但是应该让它失效，否则直接关闭会让login主界面一直隐藏")
    pass  # 这个函数不做任何事，实际上让关闭按钮失效


# def eml_login_cls_btn():
#     '''
#     这是邮箱登录窗口的关闭按钮
#     :return:
#     '''
#     print("这是邮箱登录窗口的关闭按钮")
#     pass

def pwd_login_success():
    """
    使用 用户名和密码 点击登录按钮后 进行的操作
    用户名密码登录按钮 变量名：pwd_login_button
    用户名存放于 user_name
    密码存放于 user_pwd
    :return:
    """
    user_name = name.get()
    user_pwd = passwd.get()
    # user_pwd = hashlib.sha256(user_pwd.encode('utf-8')).hexdigest()  # sha256
    res = socket_login_username(user_name, user_pwd)
    if res == 0:
        messagebox.showinfo(title='successful', message='登录成功')
        start_thread()
        login.update()
        login.destroy()
        # messagebox.showinfo(title='successful', message='登录成功')
        from contact_form import fri_form
    else:
        messagebox.showerror(title='wrong', message='登录失败，用户名或密码错误')


pwd_login_button = tkinter.Button(login, text='登录', command=pwd_login_success).grid(row=4, column=0, columnspan=2)


def email_login():
    """
    使用 邮箱地址和验证码 登录的界面
    登录按钮变量名：email_login_button
    获取验证码按钮变量名:login_get_scode，需要定义command，可以尝试将其定义在email_login中：其command连接函数名为 login_scode
    将主界面选择邮箱登录方式的按钮变量名为 email_choose_button
    需将其置于 email_login 函数之后
    :return:
    """
    login.update()
    login.withdraw()
    email_login = tkinter.Tk()
    login.title("邮箱登录")
    email_login.geometry('450x250')
    tkinter.Label(email_login, text='邮箱登录').grid(row=0, column=0, columnspan=2)
    tkinter.Label(email_login, text='邮箱地址：').grid(row=1, column=0)
    email_ad = tkinter.Entry(email_login)
    email_ad.grid(row=1, column=1)
    tkinter.Label(email_login, text='验证码：').grid(row=2, column=0, sticky=tkinter.E)
    scode = tkinter.Entry(email_login, show='*')
    scode.grid(row=2, column=1)
    # email_login.protocol('WM_DELETE_WINDOW', eml_login_cls_btn)
    email_login.resizable(0, 0)

    def email_login_success():
        """
        使用 邮箱地址和验证码 点击登录按钮后 进行的操作
        将其内置于 email_login() 中似乎可以解决变量声明带来的先后问题
        email存放于 user_email_ad
        验证码存放于 user_scode
        :return:
        """
        user_email_ad = email_ad.get()
        user_scode = scode.get()
        res = socket_login_email(user_email_ad, user_scode)
        if res == 0:
            login.update()
            login.deiconify()
            email_login.destroy()
            messagebox.showinfo(title='successful', message='登录成功')
            start_thread()
            from contact_form import fri_form
        else:
            login.update()
            login.deiconify()
            email_login.destroy()
            messagebox.showerror(title='wrong', message='登录失败，邮箱不存在或验证码错误')

    def reg_scode():
        socket_check_email(email_ad.get())

    email_login_button = tkinter.Button(email_login, text='登录', command=email_login_success).grid(row=4, column=0,
                                                                                                  columnspan=2)
    login_get_scode = tkinter.Button(email_login, text='验证', command=reg_scode).grid(row=1, column=2, columnspan=2)


email_choose_button = tkinter.Button(login, text='使用邮箱登录', command=email_login).grid(row=3, column=0, columnspan=2)


def register():
    """
    注册框 函数
    获得邮箱验证码按钮 变量名为 register_get_scode，command项需要定义,可以尝试将其定义在register中：其command连接函数名为 reg_scode
    :return:
    """
    login.update()
    login.withdraw()
    register = tkinter.Tk()
    register.title('注册')
    register.geometry('400x250')
    tkinter.Label(register, text='用户注册').grid(row=0, column=0, columnspan=2)
    register.protocol('WM_DELETE_WINDOW', register_cls_btn)
    register.resizable(0, 0)

    # 用户名输入框
    tkinter.Label(register, text='用户名：').grid(row=1, column=0, sticky=tkinter.E)
    name = tkinter.Entry(register)
    name.grid(row=1, column=1)

    # 密码输入框
    tkinter.Label(register, text='密码：').grid(row=2, column=0, sticky=tkinter.E)
    password = tkinter.Entry(register, show='*')
    password.grid(row=2, column=1)

    # 密码确认
    tkinter.Label(register, text='确认密码：').grid(row=3, column=0)
    repassword = tkinter.Entry(register, show='*')
    repassword.grid(row=3, column=1)

    # 邮箱地址输入
    tkinter.Label(register, text='邮箱地址：').grid(row=4, column=0, sticky=tkinter.E)
    email = tkinter.Entry(register)
    email.grid(row=4, column=1)

    # 邮箱验证码输入
    tkinter.Label(register, text='验证码：').grid(row=5, column=0, sticky=tkinter.E)
    scode = tkinter.Entry(register)
    scode.grid(row=5, column=1)

    def reg_scode():
        socket_check_email(email.get())

    register_get_scode = tkinter.Button(register, text='验证', command=reg_scode).grid(row=4, column=2, columnspan=2)

    # 正则匹配
    def card(input_psd):
        return True
        # string = "~!@#$%^&*()_+-*/<>,.[]\/"
        # for i in string:
        #     if i in input_psd:
        #         return True
        # return False

    # 注册的格式判断
    def registered():
        if not (any([x.isdigit() for x in name.get()]) and any([x.isalpha() for x in name.get()]) and card(name.get())):
            login.update()
            login.deiconify()
            register.destroy()
            messagebox.showerror(title='wrong', message='注册失败，用户名格式错误，必须包括字母和数字')
        elif len(password.get()) < 8:
            login.update()
            login.deiconify()
            register.destroy()
            messagebox.showerror(title='wrong', message='注册失败，密码不应少于8位')
        elif password.get() != repassword.get():
            login.update()
            login.deiconify()
            register.destroy()
            messagebox.showerror(title='wrong', message='注册失败，两次密码不相同')
        else:
            res = socket_register(name.get(), email.get(), password.get(), scode.get())
            login.update()
            login.deiconify()
            register.destroy()
            print("res ==>", res)
            if res == 0:
                messagebox.showinfo(title='successful', message='注册成功！')
            elif res == 1:
                messagebox.showerror(title='wrong', message='注册失败，用户名已存在')
            elif res == 2:
                messagebox.showerror(title='wrong', message='注册失败，邮箱已存在')
            elif res == 3:
                messagebox.showerror(title='wrong', message='注册失败，验证码错误')
            else:
                messagebox.showerror(title='wrong', message='注册失败，未知错误')

    tkinter.Button(register, text='注册', command=registered).grid(row=8, column=0, columnspan=2)


'主界面注册按钮，变量名为register_button'
register_button = tkinter.Button(login, text='注册', command=register).grid(row=7, column=0, columnspan=2)
# 开启窗口的主入口
login.mainloop()
